from tinydb import TinyDB, Query
from xjlibrary.our_file_dir import BaseDir

curpath = BaseDir.get_file_dir_absolute(__file__)
toppath = BaseDir.get_upper_dir(curpath, -2)
pickledbdir = BaseDir.get_new_path(toppath, "dbdata", "tinydb")
BaseDir.create_dir(pickledbdir)


class MTinyDB(object):
    dbpath = BaseDir.get_new_path(pickledbdir, "all.db")
    # 从文件反序列化，auto_dump 是每次写入操作都会写到文件，可以设置为False避免多次io
    db = TinyDB(dbpath)
    # 创建一个新的查询对象
    fruit = Query()

    @classmethod
    def insert(cls, dicts):
        """
        插入数据 {'name': 'John', 'age': 22}
        :return: 该insert方法返回插入文档的ID。
        """
        return cls.db.insert(dicts)

    @classmethod
    def all(cls):
        """
        返回所有文档
        :return:
        """
        return cls.db.all()

    @classmethod
    def db_iter(cls):
        """
        迭代返回数据
        :return:
        """
        for item in cls.db:
            yield item

    @classmethod
    def search(cls, fruits):
        """
        查找字典中存在的某个键值
        例子：
        匹配了关键的任何文件field与值 （也可能：）== 2!= > >= < <=
        >>> db.search(Fruit.type == 'peach')
        [{'count': 3, 'type': 'peach'}]
        >>> db.search(Fruit.count > 5)
        [{'count': 7, 'type': 'apple'}]
        :param key:  传入一个表达式 如  Fruit.type == 'peach'
        :param operator:
        :param value:
        :return:
        """
        return cls.db.search(fruits)

    @classmethod
    def update(cls, dicts, fruits):
        """
        更新
        :param dicts: 更新内容
        :param fruits: 更新条件 Fruit.type == 'apple'
        :return:
        """
        return cls.db.update(dicts, fruits)

    @classmethod
    def remove(cls, fruits):
        """
        删除文档
        :param fruits:  删除条件Fruit.count < 5
        :return:
        """
        return cls.db.remove(fruits)

    @classmethod
    def purge(cls):
        """
        丢弃所有数据以使用空数据库
        :return:
        """
        return cls.purge()

    ###########################################################
    # 以上为基础用法 高级用法以后需要时继续封装
    ###########################################################
